package com.zhanghe.study.thread.local;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhanghe
 * 验证线程本地存储
 * @Date: 2020/4/13 9:39
 */
public class ThreadLocalVariableHolder {
    private static ThreadLocal<Integer> myThreadLocal = new ThreadLocal<Integer>() {
        // 初始值默认为null 设置初始值为0
        protected Integer initialValue() {
            return 0;
        }
    };

    public static void increment() {
        myThreadLocal.set(myThreadLocal.get() + 1);
    }

    public static int get(){
        return myThreadLocal.get();
    }

    public static void main(String[] args) {
        // 线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i=0;i<3;i++){
            executorService.execute(new MyThread());
        }
        executorService.shutdown();
    }
}
